#include <unistd.h>

#include <iostream>
#include <thread>


using namespace std;


//Create thread operation
//normally
void do_some_work(){
    cout << "Normally create a thread by function name" << endl << endl;

    return;
}

void test1(){
    thread my_thread(do_some_work);

    my_thread.join();
    
    return;
}

//Create thread operation
//by function object
void do_something();
void do_something_else();

class background_task
{
public:
    void operator()()const
    {
        do_something();
        do_something_else();
    }
};

void do_something(){
    cout << "create thread by using function object" << endl;
}

void do_something_else(){
    cout << "do_something_else" << endl << endl;
}

void test2(){
    background_task f;
    thread my_thread(f);
    
    my_thread.join();

    return;
}

//Create thread operation
//by lambda expression
void test3(){
    thread my_thread([]{
        sleep(3);
        cout << "create thread by lambda expression" << endl;
        cout << endl;
    });


    cout << "main thread waiting" << endl;
    my_thread.join();

    return;
}

//alert the local variable
//if main thread destroy, local variable might be disable
/* void add(int & a){ */
/*     for(int i = 0; i < 10; i++){ */
/*         cout << "a = " << a << endl; */
/*         a++; */
/*     } */

/*     return; */
/* } */

/* void test4(){ */
/*     int a = 1; */
/*     //std::ref 用于包装按引用传递的值。*/
/*     //std::cref 用于包装按const引用传递的值。*/ 
/*     thread my_thread(add, ref(a)); */

/*     return; */
/* } */

//wait thread return
//thread.join();

void willBeJoin(){
    cout << "I will sleep 2 sec" << endl;
    sleep(2);

    return;
}

void test5(){
    thread my_thread(willBeJoin);

    my_thread.join();
    cout << "main thread has wait 2 sec" << endl;
    cout << endl;

    return;
}


int main()
{
    test1();
    sleep(1);
    test2();
    sleep(1);
    test3();
    sleep(1);
    /* test4(); */
    test5();
    sleep(1);
    return 0;
}

